﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Jage.Win32
{
    public partial class InputBox : Form
    {
        public InputBox()
        {
            InitializeComponent();
        }

        static private InputBox _form;

        static public DialogResult ShowDialog(string title, string question, out string value)
        {
            return ShowDialog(title, question, string.Empty, out value);
        }

        static public DialogResult ShowDialog(string title, string question, string initialValue, out string value)
        {
            return ShowDialog(title, question, initialValue, out value, s => true, string.Empty);
        }

        static public DialogResult ShowDialog(string title, string question, string initialValue, out string value, Func<string, bool> validator, string messageInvalidValue)
        {
            _form = new InputBox {Text = title, labelQuestion = {Text = question}, Validator = validator, MessageInvalidValue = messageInvalidValue};
            _form.textBoxValue.Text = initialValue;
            DialogResult result = _form.ShowDialog();
            value = _form.textBoxValue.Text;
            return result;
        }

        protected Func<string, bool> Validator { get; set; }

        private void textBoxValue_KeyUp(object sender, KeyEventArgs e)
        {
            button1.Enabled = !string.IsNullOrWhiteSpace(textBoxValue.Text);
        }

        private void InputBox_Activated(object sender, EventArgs e)
        {
            textBoxValue.Focus();
        }

        private void InputBox_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult == DialogResult.OK)
            {
                e.Cancel = !Validator.Invoke(textBoxValue.Text);
                if (e.Cancel)
                    MessageBox.Show(MessageInvalidValue, "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        protected string MessageInvalidValue { get; set; }
    }
}
